import json

from h5.models import OnlineUser, ChatMsg, UserGroup
from asgiref.sync import async_to_sync

from channels.layers import get_channel_layer

def user_online(uid,channel_name='',status=1):
    """
    用户上线离线
    """
    OnlineUser.objects.filter(uid=uid).delete()
    if status == 1:
        OnlineUser.objects.create(uid=uid,channel_name=channel_name)

    return


def seng_sys_msg(obj):
    text = {
        "from_id":100,
        "from":obj.get('_from'),
        "to":obj.get('_to'),
        "to_id":obj.get('id'),
        "txt":"",
        "type":1,
        "zdy":{},
        "is_qun":1
    }
    channel_layer = get_channel_layer()
    async_to_sync(channel_layer.send)(obj.get('channel_name'), {"type": "send_msg", "message": json.dumps(text)})
    return


def msg_send(message,c_name=''):
    """
    消息类型定义
    {'type': 'websocket.receive', 'text': {}}
    text:{
        from_id:发送人ID
        from：消息来源
        to:消息目的地
        to_id:接收人ID
        type:消息类型：1 添加好友 2 添加群 3 文字消息 4 语音消息 5 图片消息 6 链接消息
        txt:"消息内容",
        zdy:{}  # 自定义字段,
        is_qun:是否是群消息
    }
    ----重新定义
    {
        "_from_id":发送人ID
    }
    """
    text = json.loads(message['text'])
    to_id = text['to_id']
    is_qun = text['is_qun']
    channel_layer = get_channel_layer()
    if is_qun == 1:
        channel = OnlineUser.objects.filter(uid=to_id).last()
        if not channel:
            return 0
        text['zdy']['type'] = 1
        async_to_sync(channel_layer.send)(channel.channel_name, {"type": "send_msg", "message": json.dumps(text)})
        # ChatMsg.objects.create(type=1,msg_from=text['from_id'],msg_to=text['to_id'],text=text['txt'])
        return 1
    else:
        text['zdy']['type'] = 2
        group = list(UserGroup.objects.filter(gid=to_id).values_list('uid',flat=True))
        online_g_u = list(OnlineUser.objects.filter(uid__in=group).values_list('channel_name',flat=True))
        for i in online_g_u:
            if i == c_name:
                continue
            async_to_sync(channel_layer.send)(i, {"type": "send_msg", "message": json.dumps(text)})
        # ChatMsg.objects.create(type=2,msg_from=text['from_id'],msg_to=text['to_id'],text=text['txt'])

        return 1